package com.zeekr.orm.aop;

import com.zeekr.orm.annotation.AuthCheck;
import com.zeekr.orm.common.ErrorCode;
import com.zeekr.orm.exception.BusinessException;
import com.zeekr.orm.model.entity.User;
import com.zeekr.orm.model.enums.UserRoleEnum;
import com.zeekr.orm.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 吴文杰
 * @version 1.0
 * @since 2024/11/17 02:32
 */
@Component
@Aspect
public class AuthInterceptor {

  @Resource
  UserService userService;

  @Around("@annotation(authCheck)")
  public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
    String mustRole = authCheck.mustRole();
    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

    User loginUser = userService.getLoginUser(request);

    UserRoleEnum mustRoleValue = UserRoleEnum.getEnumByValue(mustRole);
    if (mustRoleValue == null) {
      return joinPoint.proceed();
    }

    UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserrole());

    if (userRoleEnum == null) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
    }

    if (UserRoleEnum.BAN.equals(userRoleEnum)) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
    }
    if (UserRoleEnum.ADMIN.equals(mustRoleValue)) {
      if (!UserRoleEnum.ADMIN.equals(userRoleEnum)) {
        throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
      }
    }

    return joinPoint.proceed();
  }

}
